#!/bin/bash

# 配置参数
RN_ENTRY="index.js"
ANDROID_PROJECT_PATH="android"
APK_OUTPUT_DIR="release_apks"
PGY_API_KEY="2df1691211c0f9228e141f30301aa1af" 

# 清理旧构建文件
echo "Cleaning previous build artifacts..."
rm -rf $ANDROID_PROJECT_PATH/app/src/main/assets/index.android.bundle

# 安装依赖
echo "Installing dependencies..."
npm install --frozen-lockfile || exit 1

# 生成 RN Bundle
echo "Generating React Native bundle..."
npx react-native bundle \
--entry-file $RN_ENTRY \
--platform android \
--dev false \
--minify true \
--reset-cache \
--bundle-output $ANDROID_PROJECT_PATH/app/src/main/assets/index.android.bundle \
--assets-dest $ANDROID_PROJECT_PATH/app/src/main/res/ || exit 1

# 编译 Android APK
echo "Building Android APK..."
cd $ANDROID_PROJECT_PATH && ./gradlew clean assembleRelease || exit 1

# 移动 APK 到输出目录
mkdir -p ../$APK_OUTPUT_DIR
find app/build/outputs/apk/release -name "*.apk" -exec cp {} ../$APK_OUTPUT_DIR/ \;
echo "APK saved to: ../$APK_OUTPUT_DIR"

# 上传蒲公英函数
upload_to_pgyer() {
    local apk_path=$1
    echo "Uploading $apk_path to Pgyer..."

    # 使用 API 2.0 单步上传到 /apiv2/app/upload 接口
    upload_result=$(curl -s -X POST \
        -F "_api_key=$PGY_API_KEY" \
        -F "file=@$apk_path" \
        "https://www.pgyer.com/apiv2/app/upload")

    # 检查上传结果
    # 尝试解析为 JSON 并检查 code
    if echo "$upload_result" | jq -e '.code == 0' > /dev/null; then
        echo "✅ 上传成功！"
        echo "应用页面：https://www.pgyer.com/$(echo "$upload_result" | jq -r '.data.buildKey')"
        # 您可以根据需要打印更多信息，例如：
        # echo "版本号: $(echo "$upload_result" | jq -r '.data.buildVersion')"
        # echo "更新描述: $(echo "$upload_result" | jq -r '.data.buildUpdateDescription')"
    # 检查是否是 HTML 或 XML 错误响应 (以 < 开头)
    elif echo "$upload_result" | head -n 1 | grep -q "<"; then
        echo "❌ Upload failed with server error (HTML/XML response):"
        echo "$upload_result" # 打印完整的 HTML/XML 响应
        return 1
    else
        echo "❌ Upload failed with unexpected response:"
        echo "$upload_result" # 打印其他类型的响应
        return 1
    fi
}

# 交互式选择是否上传
latest_apk=$(ls -t $APK_OUTPUT_DIR/*.apk | head -1)
echo "检测到最新 APK：$latest_apk"
read -p "是否上传到蒲公英？[y/N] " upload_choice
case "$upload_choice" in
    y|Y )
        if [ -z "$PGY_API_KEY" ]; then
            echo "未配置蒲公英API Key，请修改脚本中的PGY_API_KEY变量"
        else
            upload_to_pgyer $latest_apk
            # 您可以在这里添加检查 upload_to_pgyer 的返回值，如果失败则退出脚本
            # if [ $? -ne 0 ]; then
            #     exit 1
            # fi
        fi
        ;;
    * )
        echo "跳过上传"
        ;;
esac